package cc.yugu.yhdw.webserver.config;

import cc.yugu.yhdw.common.utils.IdUtils;
import com.whalin.MemCached.MemCachedClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 一个简单的内存缓存
 *
 * @Date:Created in 2018/6/27 11:01
 * @Author:
 * @Modified By: zjn 2018/6/27 11:01
 */
public class TokenCache {
    public final static String CACHE_KEY_TOKEN = "token:";
    private final static long CHECK_INTERVAL= 1000L * 3600 * 2 + 120;
    private final ScheduledExecutorService scheduledService = Executors.newScheduledThreadPool(2);

    public static ThreadLocal<Data> tokenCacheHolder = new ThreadLocal<Data>();

    @Autowired
    MemCachedClient memCachedClient;

    private final Map<String, Data> cache = new ConcurrentHashMap<String, Data>();

    private final Runnable cleanWorker = new Runnable() {
        @Override
        public void run() {
            List<String> list = new LinkedList<String>();

            for(Data data : cache.values()) {
                if(System.currentTimeMillis() - data.createTime >= CHECK_INTERVAL) {
                    list.add(data.token);
                }
            }

            for(String token : list) {
                cache.remove(token);
            }
        }
    };

    public TokenCache() {
        scheduledService.scheduleAtFixedRate(cleanWorker, 0, 3, TimeUnit.MINUTES);
    }

    public Data put(int id, int agentId, Date date) {
        String token = IdUtils.uuid();
        Data data = new Data();
        data.token = token;
        data.id = id;
        data.agentId = agentId;
        data.createTime = System.currentTimeMillis();

        cache.put(token, data);
        memCachedClient.set(CACHE_KEY_TOKEN + token, data, date);
        return data;
    }

    public Data get(String token) {
        String key = CACHE_KEY_TOKEN + token;

        Data data = cache.get(token);
        if(data == null) {
            data = (Data) memCachedClient.get(key);
            if(data == null) {
                return null;
            } else {
                cache.put(data.token, data);
                return data;
            }
        }
        return data;
    }

    public static class Data implements java.io.Serializable {
        public String token;
        public int id;
        public int agentId;
        public long createTime;
    }
}
